package com.genreate.util.pay.wx.config;

import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.PublicKeyVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.exception.HttpCodeException;
import com.wechat.pay.contrib.apache.httpclient.exception.NotFoundException;
import com.wechat.pay.java.core.util.PemUtil;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * 微信支付配置
 *
 * @author LYS
 * @date 2025-07-10
 */
public class WxPayConfig {
    /**
     * appid
     */
    public static String appid = "";

    /**
     * 商户号
     */
    public final static String mchid = "";

    /**
     * 商户API私钥路径
     */
    public final static String privateKeyPath = "/Users/yourname/your/path/apiclient_key.pem";
    /**
     * 公钥路径
     */
    public final static String publicKeyPath = "/Users/yourname/your/path/apiclient_key.pem";

    /**
     * 公钥id
     */
    public static final String publicKeyId = "";

    /**
     * 商户证书序列号
     */
    public final static String merchantSerialNumber = "";

    /**
     * 商户APIV3密钥
     */
    public final static String apiV3Key = "...";

    /**
     * 私钥
     */
    public final static PrivateKey privateKey = PemUtil.loadPrivateKeyFromPath(privateKeyPath);
    /**
     * 公钥
     */
    public final static PublicKey publicKey = PemUtil.loadPublicKeyFromPath(publicKeyPath);

    /**
     * 微信支付公钥验签器
     */
    public static Verifier publicKeyVerifier;
    /**
     * 平台证书验签器
     */
    public static Verifier certificateVerifier;
    /**
     * 平台证书管理器
     */
    public final static CertificatesManager certificatesManager;

    static {
        // 获取证书管理器实例
        certificatesManager = CertificatesManager.getInstance();
        // 向证书管理器增加需要自动更新平台证书的商户信息
        try {
            certificatesManager.putMerchant(mchid, new WechatPay2Credentials(mchid,
                            new PrivateKeySigner(merchantSerialNumber, privateKey)),
                    apiV3Key.getBytes(StandardCharsets.UTF_8));

            certificateVerifier = certificatesManager.getVerifier(mchid);

            publicKeyVerifier = new PublicKeyVerifier(publicKeyId, publicKey);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        } catch (HttpCodeException e) {
            e.printStackTrace();
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
